<?php


namespace app\backend\service;
use app\backend\model\AdminModel;
use app\backend\model\MerchantModel;
use app\backend\model\RoleModel;
use app\backend\validate\AdminValidate;
use app\common\RootService;
use think\Exception;

class AdminService extends RootService
{
    /**
     * 用户列表
     * @param array $params
     * @return mixed
     */
    public function lists(array $params)
    {
        $adminNames = self::adminNames();
        //状态
        $stateLabel = AdminModel::$stateLabel;
        // 数据源
        $adminList = $this->adminModel($params)->order('a.id desc')->paginate($params['limit'] ?? 10)->toArray();
        // 数据处理
        empty($adminList['data']) || array_walk($adminList['data'], function (&$row) use ($stateLabel, $adminNames) {
            empty($row['remark']) && $row['remark'] = '--';
            $row['stateLabel'] = $stateLabel[$row['state']] ?? '--';
            $row['parentName'] = $adminNames[$row['admin_id']]['real_name'] ?? $adminNames[$row['admin_id']]['admin_name'] ?: '--';
        });
        return $adminList;
    }

    /**
     * 角色列表
     * @return array
     */
    public function roleList()
    {
        $adminId = adminInfo('id');
        // 管理员列表
        $adminList = AdminModel::column('id, admin_id');
        $adminList[] = ['id' => $adminId, 'admin_id' => $adminId];
        // 我的下级用户
        $myAdminList = infiniteRecursionAdmin($adminList, $adminId);
        // 角色列表
        return RoleModel::where(['admin_id' => array_column($myAdminList, 'id')])->column('id, role_name');
    }

    /**
     * 个人详情
     * @return mixed|object|\think\App
     * @throws \app\common\RootException
     */
    public function info()
    {
        $adminInfo = adminInfo();
        // 角色名称
        $adminInfo['roleName'] = RoleModel::where(['id' => $adminInfo['role_id']])->value('role_name');
        return $adminInfo;
    }

    /**
     * 更新账户信息
     * @param array $params
     * @return string[]
     * @throws \app\common\RootException
     */
    public function modify(array $params)
    {
        $adminInfo = adminInfo();
        // 数据校验
        $this->verify($params, 'modify');
        // 更新内容
        $updateData = ['real_name' => $params['real_name'], 'mobile' => $params['mobile'], 'email' => $params['email'],
            'remarks' => $params['remarks']];
        AdminModel::where(['id' => $adminInfo['id']])->update($updateData) || $this->errorException('保存失败');
        // 过期时间
        $tokenExpire = env('app.admin_token_expire', 240) * 60;
        // 获取token
        $accessToken = $this->issueAdminToken($adminInfo['id']);
        // 设置COOKIE
        cookie('accessToken', $accessToken, $tokenExpire);
        // 更新缓存
        cache(md5($accessToken . 'admin' . $adminInfo['id']), AdminModel::where(['id' => $adminInfo['id']])->find()->toArray(), $tokenExpire);
        return ['msg' => '个人资料更新成功!!!', 'preload' => true];
    }

    /**
     * 重置密码
     * @param array $params
     * @return array
     * @throws \app\common\RootException
     */
    public function resetPwd(array $params)
    {
        // 数据校验
        $this->verify($params, 'resetPwd');
        // 修改密码
        $updateData = ['password' => $this->encAdminPwd($params['password'])];
        AdminModel::where(['id' => adminInfo('id')])->update($updateData) || $this->errorException('密码修改失败');
        // 重置密码并退出登录
        return ['msg' => '密码修改成功', 'redirect' => url('Index/logout')->build()];
    }

    /**
     * 详情
     * @param int $adminId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail(int $adminId)
    {
        return AdminModel::where(['id' => $adminId])->find()->toArray();
    }

    /**
     * 修改状态
     * @param array $params
     * @return string[]
     * @throws \app\common\RootException
     */
    public function changeState(array $params)
    {
        AdminModel::where(['id' => $params['id']])->update(['state' => $params['state'] ? 0 : 1]) || $this->errorException('状态修改失败');
        return ['msg' => '状态修改成功', 'reload' => 'true'];
    }

    /**
     * 新增操作
     * @param array $params
     * @return array
     * @throws \app\common\RootException
     */
    public function add(array $params)
    {
        // 参数检验
        $this->verify($params, 'add');
        // 新增操作
        $insertData = ['admin_id' => adminInfo('id'), 'password' => $this->encAdminPwd($params['password']),
            'real_name' => $params['realName'], 'admin_name' => $params['adminName'], 'mobile' => $params['mobile'],
            'email' => $params['email'], 'role_id' => $params['roleId'], 'remark' => $params['remark'],
            'state' => $params['state']];
        AdminModel::create($insertData) || $this->errorException('添加失败');
        // 添加成功
        return ['msg' => '添加成功', 'preload' => true];
    }

    /**
     * 编辑操作
     * @param array $params
     * @return array
     * @throws \app\common\RootException
     */
    public function edit(array $params)
    {
        // 参数检验
        $this->verify($params, 'edit');
        // 新增操作
        $updateData = ['real_name' => $params['realName'], 'mobile' => $params['mobile'], 'email' => $params['email'],
            'role_id' => $params['roleId'], 'remark' => $params['remark'], 'state' => $params['state']];
        // 更新密码
        empty($params['passwd']) || $updateData['password'] = $this->encAdminPwd($params['passwd']);
        AdminModel::where(['id' => $params['id']])->update($updateData) || $this->errorException('更新失败');
        // 添加成功
        return ['msg' => '修改成功', 'preload' => true];
    }

    /**
     * 删除操作
     * @param int $adminId
     * @return array
     * @throws \app\common\RootException
     */
    public function del(int $adminId)
    {
        // 删除操作
        AdminModel::where(['id' => $adminId])->delete() || $this->errorException('删除失败');
        // 删除成功
        return ['msg' => '删除成功', 'reload' => true];
    }

    /**
     * 管理员名称
     * @return array
     */
    public static function adminNames(int $adminId = 0, bool $select = false)
    {
        $adminNameList = AdminModel::column('real_name' . ($select ? '' : ',admin_name'), 'id');
        return empty($adminId) ? $adminNameList : ($adminNameList[$adminId]['real_name'] ?? '');
    }

    /**
     * 基础校验
     * @param array $params
     * @param string $scene
     * @throws \app\common\RootException
     */
    protected function verify(array $params, string $scene)
    {
        $validate = new AdminValidate();
        $validate->scene($scene)->check($params) || $this->errorException($validate->getError());
        // 用户名校验
        if (in_array($scene, ['add'])) {
            $where = [['admin_name', '=', $params['adminName']]];
            empty($params['id']) || $where[] = [['id', '<>', $params['id']]];
            AdminModel::where($where)->count() && $this->errorException("用户名称【{$params['adminName']}】已存在，请勿重复添加");
        }
        // 原密码校验
        if (in_array($scene, ['resetPwd']) && !$this->checkAdminPwd($params['oldPassword'], adminInfo('password'))) {
            $this->errorException('原密码校验失败');
        }
    }

    /**
     * 管理员模型
     * @param array $params
     * @return mixed
     */
    protected function adminModel(array $params)
    {
        $adminList = infiniteRecursionAdmin(AdminModel::column('id, admin_id'), adminInfo('id'));
        // 筛选条件
        $where = [['a.id', 'in', array_column($adminList, 'id')]];
        // 手机号码筛选
        empty($params['mobile']) || $where[] = ['a.mobile', 'like', $params['mobile'] . '%'];
        // 用户名、真实姓名筛选
        empty($params['adminName']) || $where[] = ['a.admin_name|a.real_name', 'like', $params['adminName'] . '%'];
        // 筛选字段
        $fields = ['r.role_name', 'a.id', 'a.admin_id', 'a.admin_name', 'a.real_name', 'a.mobile', 'a.remark', 'a.state',
            'a.create_time', 'a.login_time'];
        // 筛选结果
        return AdminModel::alias('a')->join(['sys_role' => 'r'], 'a.role_id = r.id')->where($where)->field($fields);
    }
}